from typing import Dict, Optional
from datetime import datetime, timedelta
from app.config import settings

class Session:
    """会话类"""
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.history = []
        self.last_active = datetime.now()
        
    def add_message(self, role: str, content: str) -> None:
        """添加消息到历史记录"""
        self.history.append({"role": role, "content": content})
        if len(self.history) > settings.MAX_HISTORY_LENGTH:
            self.history.pop(0)
        self.last_active = datetime.now()
        
    def is_expired(self) -> bool:
        """检查会话是否过期"""
        return (datetime.now() - self.last_active).seconds > settings.CONVERSATION_TIMEOUT

class SessionManager:
    """会话管理器"""
    def __init__(self):
        self.sessions: Dict[str, Session] = {}
        
    def get_session(self, session_id: str) -> Session:
        """获取或创建会话"""
        if session_id not in self.sessions:
            self.sessions[session_id] = Session(session_id)
        return self.sessions[session_id]
        
    def cleanup_expired(self) -> None:
        """清理过期会话"""
        expired = [
            sid for sid, session in self.sessions.items() 
            if session.is_expired()
        ]
        for sid in expired:
            del self.sessions[sid] 